package
{
	import flash.desktop.NativeApplication;
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.InvokeEvent;
	import flash.events.KeyboardEvent;
	import flash.events.LocationChangeEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.html.HTMLLoader;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.navigateToURL;
	import flash.system.LoaderContext;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	
	/**
	 * 咖啡牛
	 * version=20201014
	 */
	//545x383	1280*770
	[SWF(backgroundColor="#000000", width="545", height="384", frameRate="60", quality="LOW")]
	public class Mu extends Sprite
	{
		/**
		 * 微端的入口网址
		 */
		private const WD_ENTRY_URL:String = "http://mu2.kafeiniu.com/dlq/";
		/**
		 * 选服匹配地址字符串
		 */
		private const SERVER_URL_MATCH:String = "my.kafeiniu.com/index.php/app/mu2";
		
		private var htmlLoader:HTMLLoader;
		private var flashvars:Object;
		private var entryUrl:String;
		
		private var oldid:String;  
		private var reg:RegExp = /<id>.*<\/id>/;  
		
		public function Mu()
		{
			windowedapplication_addedToStageHandler();
		}
		
		protected function windowedapplication_addedToStageHandler():void {
			var time:String = new Date().getTime()+"";
			var newid:String = "<id>mu"+time+"</id>";
			var f:File =new File(File.applicationDirectory.resolvePath("META-INF/AIR/application.xml").nativePath);
			if(f.exists) {
				var fs:FileStream = new FileStream();
				fs.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				fs.open(f,FileMode.READ);
				var str:String = new String(fs.readUTFBytes(fs.bytesAvailable));
				oldid = str.match(reg).toString();
				str = str.replace(reg,newid);
				fs.open(f,FileMode.WRITE);
				fs.writeUTFBytes(str);
				fs.close();
			}
			
			setStageState();
			inithtmlLoader();
			
			//有多个在运行的程序时只关闭一个运行程序就无法再打开新程序  
			//必须监听系统最后一个相同程序关闭时，才能初始化id  
			//解决办法：  
			//记录运行前id,若为初始ID则在关闭该程序时初始化id,否则不操作  
			if(oldid == "<id>mu</id>") {
				this.addEventListener(Event.CLOSE, returnId);
			}
		}
		
		private function onGetParameter():void {
			NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvokeEvent); 	
		}
		
		private var arguments:Array;
		private function onInvokeEvent(invocation:InvokeEvent):void {
			arguments = invocation.arguments; 
			NativeApplication.nativeApplication.removeEventListener(InvokeEvent.INVOKE, onInvokeEvent); 
		}
		
		private function setStageState () : void {
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.addEventListener(KeyboardEvent.KEY_UP, onStageKeyUp);
			stage.addEventListener("WEIDUAN_SHUAXIN", onRestart);
		}
		
		private function inithtmlLoader():void {
			if(htmlLoader == null) {
				htmlLoader = new HTMLLoader();
			}
			htmlLoader.width = 1800;
			htmlLoader.height = 1024;
			var urlReq:URLRequest = new URLRequest(this.WD_ENTRY_URL);
			htmlLoader.addEventListener(flash.events.LocationChangeEvent.LOCATION_CHANGE, handleLoad);
			htmlLoader.addEventListener(Event.COMPLETE, onComplete);
			htmlLoader.load(urlReq);
			addChild(htmlLoader);
		}
		
		private function onComplete(e:Event):void {
			var document:Object = HTMLLoader(e.currentTarget).window.document;
			var anchors:Object = document.getElementsByTagName("a");
			
			if(anchors != null) {
				for(var i:Number=0; i < anchors.length; i++) {
					anchors[i].onmouseup = function():void {
						var s1:String = arguments[0].currentTarget.href;
						var s2:String = arguments[0].currentTarget.target;
						if(s1.indexOf("javascript:")<0) {
							if(s2 != "") {
								navigateToURL(new URLRequest(s1),"_blank");
							}
						}
					}
				}
			}
		}
		
		private function handleLoad(event:flash.events.LocationChangeEvent):void {
			var d1:String = event.target.location;
			if(d1.indexOf(this.SERVER_URL_MATCH) > -1) {
				removeChild(htmlLoader);
				htmlLoader.removeEventListener(flash.events.LocationChangeEvent.LOCATION_CHANGE, handleLoad);
				htmlLoader.removeEventListener(Event.COMPLETE, onComplete);
				htmlLoader = null;
				trace("d1="+d1);
				var loader:URLLoader = new URLLoader ();
				loader.addEventListener(Event.COMPLETE, onFindLoginUrl);
				loader.load(new URLRequest(d1));
			}
		}
		
//    <iframe scrolling="no" frameborder="0" allowTransparency="true" width="100%" height="100%" src="http://ly.mu2.zhaouc.com/kafeiniu/login?uid=100206573&platform=kafeiniu1&gkey=mu2&skey=564&time=1610420741&is_adult=1&exts=&back_url=http%3A%2F%2Fmu2.kafeiniu.com%2Fdlq%2F&sign=8e40c2509d4e544b761f43aaafe2a53f&type=pc&qudao=0&recharge=http%253A%252F%252Fpay.kafeiniu.com%252F%253FAppID%253D1%2526ZoneID%253D1%2526ServerID%253D564%2526u%253D18601708436&uname=18601708436" id="gameinfo"></iframe>
		private function onFindLoginUrl(event:Event):void {
			var d:Object = event.target;
			var d1:String = d.data;
//			trace("onFindLoginUrl="+d1);
			var d2:Array = d1.split("\n");
			var d3:Array = d2.filter(onCheck3);
			var s1:String;
			var url:String;
			for(var i:int=0;i<d3.length;i++) {
				s1 = d3[i];
				var d4:Array = s1.split('src="');
				var s2:String = d4[1];
				var d5:Array = s2.split('"');
				url = d5[0];
				trace("url="+url);
				break;
			}
			if(url != null) {
				var loader:URLLoader  = new URLLoader ();
				loader.addEventListener(Event.COMPLETE, onCompleteHandler);
				loader.load(new URLRequest(url));
			}
		}
		
		private function onCompleteHandler(event:Event):void {
			var d:Object = event.target;
			var d1:String = d.data;
//			trace("html="+d1);
			var d2:Array = d1.split("\n");
			var d3:Array = d2.filter(onCheck);
			flashvars = {};
			var s1:String;
			var s2:String;
			var d5:Array;
			var s3:String;
			var s4:String;
			var s5:String;
			var reg:RegExp = new RegExp('"',"g");
			var i:int=0;
			for(;i<d3.length;i++) {
				s1 = d3[i];
				s2 = s1.split(";")[0];
				d5 = s2.split("=");
				s3 = d5[1];//值
				s3 = s3.replace(reg, "");
				s3 = s3.replace(/\s+/g,"");
				s4 = d5[0];
				s5 = s4.split(".")[1];
				s5 = s5.replace(/\s+/g,"");
				flashvars[s5] = s3;
			}
			
			d3 = d2.filter(onCheck2);
			for(i=0;i<d3.length;i++) {
				s1 =d3[i];
				s2 = s1.split(",")[0];
				s2 = s2.replace(reg, "");
				s2 = s2.replace(/\s+/g,"");
				entryUrl = s2;
			}
			trace("entryUrl = "+entryUrl);
			if(entryUrl != null) {
				addLoadSwf();
			}
			else {
				//重新登录
				windowedapplication_addedToStageHandler();
			}
		}
		
		private function onCheck(value:*, index:int, arr:Array):Boolean {
			var f:Boolean = value.indexOf("flashvars.")>-1;
			return f;
		}
		//找出 http://cdn1.qiji.zhaouc.com/njdclient/Entry.swf?v=MJ3N8L
		private function onCheck2(value:*, index:int, arr:Array):Boolean {
			var f:Boolean = value.indexOf("Entry.swf")>-1;
			return f;
		}
		
		private function onCheck3(value:*, index:int, arr:Array):Boolean {
			var f:Boolean = value.indexOf('<iframe scrolling')>-1;
			return f;
		}
		
		private function addLoadSwf():void {
			trace("addLoadSwf");
			var ur:URLRequest = new URLRequest();
			ur.url = entryUrl;
			ur.method = URLRequestMethod.GET;
			var entryLoader:URLLoader = new URLLoader();
			entryLoader.dataFormat = URLLoaderDataFormat.BINARY;
			entryLoader.addEventListener(Event.COMPLETE, onBytesLoader);
			entryLoader.load(ur);
		}
		
		private function onBytesLoader(event:Event):void {
			trace("onBytesLoader");
			var entryLoader:URLLoader = event.target as URLLoader;
			if(entryLoader != null) {
				var data:ByteArray = entryLoader.data;
				var con:LoaderContext = new LoaderContext();
				con.allowCodeImport = true;
				var loader:Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onEntryCompleteHandler);
				loader.loadBytes(data, con);
				
				entryLoader.removeEventListener(Event.COMPLETE, onBytesLoader);
			}
		}
		
		private function onEntryCompleteHandler(event:Event):void {
			trace("onEntryCompleteHandler");
			var loaderinfo:LoaderInfo = event.target as LoaderInfo;
			if(loaderinfo != null) {
				var entryDisplay:DisplayObject = loaderinfo.content;
				stage.addChild(entryDisplay);
				(entryDisplay["onDesktopHandle"] as Function).call(null, flashvars);
				loaderinfo.removeEventListener(Event.COMPLETE, onEntryCompleteHandler);
				
				stage.nativeWindow.visible = true;
				stage.nativeWindow.maximize();
			}
		}
		
		
		private function errorHandler(event:IOErrorEvent):void { 
			trace("IOErrorEvent "+event.text);
		} 
		
		protected function returnId(e:Event):void  
		{
			var f:File =new File(File.applicationDirectory.resolvePath("META-INF/AIR/application.xml").nativePath);
			if(f.exists) {
				var fs:FileStream = new FileStream();
				fs.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				fs.open(f,FileMode.READ);        
				var str:String = new String(fs.readUTFBytes(fs.bytesAvailable));  
				str = str.replace(reg,oldid);    
				fs.open(f,FileMode.WRITE);  
				fs.writeUTFBytes(str);   
				fs.close();
			}
		}
		
		private function onStageKeyUp(e:KeyboardEvent):void {
			if(e.keyCode == Keyboard.F5) {
				onRestart();
			}
		}
		
		private function onRestart(e:Event=null):void {
			var appFile:File = File.applicationDirectory.resolvePath("奇迹重生.exe");
			var nps:NativeProcessStartupInfo = new NativeProcessStartupInfo();
			nps.executable = appFile;
			var procces:NativeProcess = new NativeProcess();
			procces.start(nps);
			stage.nativeWindow.close();
		}
		
	}
}